var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();

// set cors
app.use((req, res, next) => {
  res.set({
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Credentials': true,
    'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
    'Access-Control-Allow-Headers': 'Content-Type'
  })
  if (req.method === 'OPTIONS') {
    return res.sendStatus(200)
  }
  res._err = function (err, code = 1) {
    res.json({
      code: code,
      msg: err instanceof Error ? err.message : err
    })
  }
  res._ok = function (data, msg = 'success', code = 0) {
    res.json({
      code: code,
      msg: msg,
      data: data
    })
  }
  next()
})

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'pages.md')))

app.use('/', indexRouter);
app.use('/users', usersRouter);

module.exports = app;
